package com.cskaoyan.catmall.service.Impl;

import com.cskaoyan.catmall.dao.StorageDao;
import com.cskaoyan.catmall.model.bo.BaseParamBo;
import com.cskaoyan.catmall.model.bo.StorageBo;
import com.cskaoyan.catmall.model.pojo.FileUploadPojo;
import com.cskaoyan.catmall.model.vo.*;
import com.cskaoyan.catmall.service.StorageService;
import com.cskaoyan.catmall.utils.FIleUploadUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @Author: 逍遥子
 * @Date: 2022/01/08/15:21
 * @Description:
 */
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageDao storageDao;

    @Override
    public StorageVo selectStorage(StorageBo storageBo) {

        Integer page = storageBo.getPage(); // 第几页
        Integer limit = storageBo.getLimit(); // 一页显示几条数据

        PageHelper.startPage(page, limit);

        List<StorageVo.ListDTO> listDTOS = storageDao.selectStorage(storageBo);

        PageInfo pageInfo = new PageInfo(listDTOS);

        long total = pageInfo.getTotal(); // 查询数据总条数
        int pages = pageInfo.getPages();  // 计算总共几页数据

        // 封装视图层对象
        return new StorageVo(total, pages, limit, page, listDTOS);
    }

    @Override
    public int deleteStorage(StorageVo.ListDTO listDTO) {
        return storageDao.deleteStorage(listDTO);
    }

    @Override
    public ImageVo uploadFile(MultipartFile file) {
        // 获取文件信息
        String originalFilename = file.getOriginalFilename(); //获取文件名
        String contentType = file.getContentType();// 文件类型
        long size = file.getSize();// 文件大小
        String url = null;
        String key = null;

        try {
            url = FIleUploadUtil.upload(file.getInputStream());
            //key = url.split("/")[1];
            key = url.substring(url.lastIndexOf("/") + 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 封装一个文件上传对象
        FileUploadPojo fileUploadPojo = new FileUploadPojo();
        fileUploadPojo.setKey(key);
        fileUploadPojo.setName(originalFilename);
        fileUploadPojo.setType(contentType);
        fileUploadPojo.setSize(size);
        fileUploadPojo.setUrl(url);
        storageDao.uploadFile(fileUploadPojo);
        return new ImageVo(fileUploadPojo.getId(), key, originalFilename, contentType, size, url, null, null);
    }

    @Override
    public int updateFileName(StorageVo.ListDTO listDTO) {
        return storageDao.updateFileName(listDTO);
    }
}
